
import org.semanticweb.owlapi.apibinding.OWLManager
import org.semanticweb.owlapi.model.*
import org.semanticweb.owlapi.reasoner.*
import org.semanticweb.owlapi.profiles.*
import org.semanticweb.owlapi.util.*
import org.semanticweb.owlapi.io.*
import org.semanticweb.elk.owlapi.*


class BootStrap {

  String formatClassName(String c) {
    c.replaceAll("<http://purl.obolibrary.org/obo/","").replaceAll("_",":").replaceAll(">","")
  }


  
  Map<String, Set<String>> processAllOntologies() {
    def res = [:]
    new File("data/").eachFile{ file ->
      if (file.toString().indexOf("_")==-1 && file.toString().indexOf("-")==-1) {
	println "Processing $file"
	OWLOntologyManager manager = OWLManager.createOWLOntologyManager()
	OWLDataFactory fac = manager.getOWLDataFactory()
	try {
	  OWLOntology ont = manager.loadOntologyFromOntologyDocument(file)
	  OWLReasonerFactory reasonerFactory = null
	  ConsoleProgressMonitor progressMonitor = new ConsoleProgressMonitor()
	  OWLReasonerConfiguration config = new SimpleConfiguration(progressMonitor)
	  OWLReasonerFactory f1 = new ElkReasonerFactory()
	  OWLReasoner reasoner = f1.createReasoner(ont)
	  reasoner.precomputeInferences(InferenceType.CLASS_HIERARCHY)
	  
	  ont.getClassesInSignature().each { cl ->
	    def clearClassName = formatClassName(cl.toString())
	    Set<String> supSet = new TreeSet<String>()
	    supSet.add(clearClassName)
	    reasoner.getSuperClasses(cl, false).getFlattened().each { sup ->
	      if (!sup.isOWLThing()) {
		def clstr = formatClassName(sup.toString())
		supSet.add(clstr)
	      }
	    }
	    if (res[clearClassName] == null) {
	      res[clearClassName] = supSet
	      //	      println "Set $clearClassName ("+supSet.size()+")"
	    } else {
	      res[clearClassName].addAll(supSet)
	    }
	  }
	} catch (Exception E) {
	  println "Parse error in $file"
	}
      }
    }
    return res
  }

  def init = { servletContext ->
    println "initializing" 
    def omap = processAllOntologies()
    println omap.size()
    servletContext.setAttribute("omap", omap)
  }
}